package com.terry.sp.service.impl;

import com.alibaba.fastjson.JSON;
import com.terry.sp.core.services.AbstractService;
import com.terry.sp.core.exception.ServiceException;
import com.terry.sp.dao.PrintTaskMapper;
import com.terry.sp.model.PrintTask;
import com.terry.sp.service.PrintTaskService;
import com.terry.sp.utils.FileHelper;
import com.terry.sp.websocket.DeviceServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;

@Service
@Slf4j
@Transactional
public class PrintTaskServiceImpl extends AbstractService<PrintTask> implements PrintTaskService {
    @Value("${TempFilePath}")
    private String TempFilePath;

    @Resource
    private PrintTaskMapper printTaskMapper;

    @Override
    public PrintTask getTaskByDeviceId(int deviceId) {
        return printTaskMapper.getTaskByDeviceId(deviceId);
    }

    @Override
    public PrintTask getTaskById(int taskId) {
        return printTaskMapper.selectByPrimaryKey(taskId);
    }

    @Transactional
    @Override
    public void printTasks(int[] taskIds) {
        for (int id : taskIds) {
            printTaskMapper.printTaskById(id);
        }
    }

    @Override
    public boolean finishTaskById(int taskId) {
        printTaskMapper.finishTaskById(taskId);
        PrintTask task = printTaskMapper.selectByPrimaryKey(taskId);

        File file = new File(TempFilePath + "/" + task.getFilename());
        if (file.exists() && file.isFile()) {
            return file.delete();
        }
        return false;
    }

    @Override
    public void addTask(MultipartFile file, PrintTask task) {
        if (null == file) throw new ServiceException("文件不能为空!");

        boolean localFile = FileHelper.createLocalFile(TempFilePath, file);
        if (!localFile) {
            throw new ServiceException("创建本地文件失败,文件上传失败!");
        }

        // 保存到数据库
        save(task);

        DeviceServer.sendInfo(JSON.toJSONString(task), task.getDeviceId());
    }

}
